import logging
import pymysql


class DBUtil(object):

    def __init__(self, host="localhost", user="root", password="root",
                 database="dbname", port=3306, charset="utf8"):
        self.connect = pymysql.connect(host=host, user=user, password=password,
                                       database=database, port=port)

        self.cursor = self.connect.cursor()

    def __del__(self):
        self.cursor.close()
        self.connect.close()

    def dql_one(self, sql):
        num = self.cursor.execute(sql)
        logging.info(f'影响行数：{num}')
        return self.cursor.fetchone()

    def dql_many(self, sql, n):
        num = self.cursor.execute(sql)
        logging.info(f'影响行数：{num}')
        return self.cursor.fetchmany(n)

    def dql_all(self, sql):
        num = self.cursor.execute(sql)
        logging.info(f'影响行数：{num}')
        return self.cursor.fetchall()

    def dml_sql(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            logging.info(f'执行错误：{e}')
            self.connect.rollback()
        else:
            self.connect.commit()


if __name__ == '__main__':
    dbUtil = DBUtil(host='211.103.136.244', port=7061,
                    user='student', password='iHRM_student_2021',
                    database='ihrm')

    sql = 'select * from bs_user limit 10'
    dbUtil.dql_all(sql)
